<template>
  <div class="group-management">
    <div class="page-header">
      <h2>拼团管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="拼团名称">
          <el-input v-model="searchForm.groupName" placeholder="请输入拼团名称" clearable />
        </el-form-item>
        <el-form-item label="拼团状态">
          <el-select v-model="searchForm.groupState" placeholder="请选择状态" clearable>
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已暂停" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchGroups">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增拼团
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="groupList" v-loading="loading" stripe>
        <el-table-column prop="groupId" label="拼团ID" width="80" />
        <el-table-column prop="groupName" label="拼团名称" width="200" />
        <el-table-column prop="beforePrice" label="原价" width="120">
          <template #default="{ row }">
            ¥{{ row.beforePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="afterPrice" label="拼团价" width="120">
          <template #default="{ row }">
            ¥{{ row.afterPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="groupPeople" label="成团人数" width="120" />
        <el-table-column prop="groupState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateType(row.groupState)">
              {{ getStateText(row.groupState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editGroup(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteGroup(row.groupId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑拼团' : '新增拼团'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="groupForm" :rules="groupRules" ref="groupFormRef" label-width="120px">
        <el-form-item label="拼团名称" prop="groupName">
          <el-input v-model="groupForm.groupName" placeholder="请输入拼团名称" />
        </el-form-item>
        <el-form-item label="原价" prop="beforePrice">
          <el-input v-model="groupForm.beforePrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="拼团价" prop="afterPrice">
          <el-input v-model="groupForm.afterPrice" placeholder="请输入拼团价" />
        </el-form-item>
        <el-form-item label="成团人数" prop="groupPeople">
          <el-input-number v-model="groupForm.groupPeople" :min="2" :max="100" placeholder="请输入成团人数" />
        </el-form-item>
        <el-form-item label="拼团状态" prop="groupState">
          <el-select v-model="groupForm.groupState" placeholder="请选择状态">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已结束" :value="2" />
            <el-option label="已暂停" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="groupForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="groupForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { groupApi } from '@/api/group'

// 响应式数据
const loading = ref(false)
const groupList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const groupFormRef = ref()

// 搜索表单
const searchForm = reactive({
  groupName: '',
  groupState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 拼团表单
const groupForm = reactive({
  groupId: null,
  groupName: '',
  beforePrice: '',
  afterPrice: '',
  groupPeople: 2,
  groupState: null,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const groupRules = {
  groupName: [
    { required: true, message: '请输入拼团名称', trigger: 'blur' }
  ],
  beforePrice: [
    { required: true, message: '请输入原价', trigger: 'blur' }
  ],
  afterPrice: [
    { required: true, message: '请输入拼团价', trigger: 'blur' }
  ],
  groupPeople: [
    { required: true, message: '请输入成团人数', trigger: 'blur' }
  ],
  groupState: [
    { required: true, message: '请选择拼团状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取状态类型
const getStateType = (state) => {
  const stateMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return stateMap[state] || 'info'
}

// 获取状态文本
const getStateText = (state) => {
  const stateMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束',
    3: '已暂停'
  }
  return stateMap[state] || '未知'
}

// 搜索拼团
const searchGroups = async () => {
  loading.value = true
  try {
    const response = await groupApi.getGroupList(searchForm)
    if (response.code === 200) {
      groupList.value = response.data || []
      pagination.total = groupList.value.length
    }
  } catch (error) {
    console.error('搜索拼团失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    groupName: '',
    groupState: null
  })
  searchGroups()
}

// 编辑拼团
const editGroup = (row) => {
  isEdit.value = true
  Object.assign(groupForm, row)
  showAddDialog.value = true
}

// 删除拼团
const deleteGroup = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个拼团活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await groupApi.deleteGroup(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchGroups()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除拼团失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await groupFormRef.value.validate()

    // 格式化日期时间数据，将其转换为基础格式 (LocalDateTime)
    const formData = { ...groupForm }
    if (formData.startTime) {
      // 确保日期时间格式正确，转换为后端可接受的格式
      formData.startTime = formatDateTimeForBackend(formData.startTime)
    }
    if (formData.endTime) {
      formData.endTime = formatDateTimeForBackend(formData.endTime)
    }

    const response = isEdit.value
      ? await groupApi.updateGroup(formData)
      : await groupApi.addGroup(formData)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchGroups()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 格式化日期时间为后端可接受的格式
const formatDateTimeForBackend = (dateTime) => {
  if (!dateTime) return null
  
  // 处理字符串格式的日期时间
  if (typeof dateTime === 'string') {
    // 如果字符串包含 T，替换为空格
    if (dateTime.includes('T')) {
      return dateTime.replace('T', ' ').substring(0, 19)
    }
    // 如果已经是正确格式，直接返回
    return dateTime
  }
  
  // 如果是Date对象，转换为字符串
  if (dateTime instanceof Date) {
    const year = dateTime.getFullYear()
    const month = String(dateTime.getMonth() + 1).padStart(2, '0')
    const day = String(dateTime.getDate()).padStart(2, '0')
    const hours = String(dateTime.getHours()).padStart(2, '0')
    const minutes = String(dateTime.getMinutes()).padStart(2, '0')
    const seconds = String(dateTime.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  return dateTime
}

// 重置表单
const resetForm = () => {
  Object.assign(groupForm, {
    groupId: null,
    groupName: '',
    beforePrice: '',
    afterPrice: '',
    groupPeople: 2,
    groupState: null,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  groupFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchGroups()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchGroups()
}

// 初始化
onMounted(() => {
  searchGroups()
})
</script>

<style scoped>
.group-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>